<?php

namespace App\B2BProject\Custom\Business;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Issue extends Model
{
    protected $guarded = ['created_at', 'updated_at'];
    /**
     * 获取当前咨询的回复
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function reply()
    {
        return $this->hasOne('App\B2BProject\Custom\Business\Issue', 'reply_id', 'id');
    }

    /**
     * 获取该咨询的发布者
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function member()
    {
        return $this->belongsTo('App\B2BProject\Custom\Member', 'member_id', 'id');
    }

    /**
     * 获取该咨询询问的商品
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function goods()
    {
        return $this->belongsTo('App\B2BProject\Custom\Business\Goods', 'goods_id', 'id');
    }

    /**
     * @param Builder $builder
     *
     * @return Builder|static
     */
    public function scopeHasReply(Builder $builder)
    {
        return $builder->has('reply');
    }

    /**
     * 获取可回复的咨询
     *
     * @param Builder $builder
     *
     * @return Builder
     */
    public function scopeEnableToReply(Builder $builder)
    {
        return $builder->whereNotNull('goods_id');
    }

    /**
     * 获取未回复的咨询
     *
     * @param Builder $builder
     *
     * @return Builder
     */
    public function scopeWithoutReplied(Builder $builder)
    {
        return $builder->where('replied', false)->whereNotNull('goods_id');
    }

    /**
     * 获取已回复的咨询
     *
     * @param Builder $builder
     *
     * @return mixed
     */
    public function scopeIsReplied(Builder $builder)
    {
        return $builder->where('replied', true)->whereNotNull('goods_id');
    }

    /**
     * 获取当前对象是否可回复
     *
     * @return bool
     */
    public function canReply()
    {
        if (is_null($this->goods_id)) {
            return false;
        }

        return true;
    }

    /**
     * 创建咨询的回复
     *
     * @param $content
     *
     * @return $this
     */
    public function createReply($content)
    {
        if ($this->canReply()) {
            $reply = new Issue();
            $reply->content = $content;
            $reply->save();

            \Auth::user()->issues()->save($reply);

            $this->reply()->save($reply);
            $this->replied = true;

            $this->save();
            return $this;
        }

        throw new \BadMethodCallException;
    }
}
